package com.zzty.daoimpl;

import com.zzty.common.DBUtil;
import com.zzty.common.DBUtilPool;
import com.zzty.common.Split;
import com.zzty.dao.SelfExamDao;
import com.zzty.entity.Question;
import com.zzty.entity.SelfExam;
import com.zzty.entity.SelfExamTransaction;
import com.zzty.entity.SelfQuestion;
import com.zzty.entity.SelfStudentHomework;
import sun.security.pkcs11.Secmod;


import javax.xml.parsers.DocumentBuilder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SelfExamDaoImpl implements SelfExamDao {

    public String addSelfTransaction(int userId) {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(d);
        String date2 = sdf2.format(d);
        System.out.println("现在时间为：" + date);
        String questionIds = null;
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement(
                    "select * from selfExam where date=?");
            preparedStatement.setString(1, date);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                questionIds = resultSet.getString("questionId");
                int selfExamId = resultSet.getInt("id");
                PreparedStatement pst = cn.prepareStatement(
                        "insert into selfExamTransaction (selfExamId,userId,startTime) values(?,?,?)");
                pst.setInt(1, selfExamId);
                pst.setInt(2, userId);
                pst.setString(3, date2);
                pst.executeUpdate();
                System.out.println("在selfExamTransaction插入数据成功；"
                        + "selfExamId    " + selfExamId + "  userId  " + userId + "  date2   " + date2 + "   questionId is " + questionIds);

            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("daoImpl questionIds :" + questionIds);
        return questionIds;

    }

    @Override
    public void addStartTransaction(Integer selfExamId, Integer userId, String nowDate) {
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement pst = cn.prepareStatement(
                    "insert into selfExamTransaction (selfExamId,userId,startTime) values(?,?,?)");
            pst.setInt(1, selfExamId);
            pst.setInt(2, userId);
            pst.setString(3, nowDate);
            pst.executeUpdate();
            System.out.println("在transaction插入数据成功！");
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            System.out.println("在transaction插入数据失败！");
        }
    }

    public Boolean checkLogIn(int id) {
        Boolean checkLogIn = false;
        Date date = new Date();
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement(
                    "select * from selfExamTransaction where userId=? and spendTime is not null");
            preparedStatement.setInt(1, id);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                checkLogIn = true;

            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return checkLogIn;
    }

    @Override
    public Boolean checkLogIn(Integer selfExamId, Integer userId) {
        Boolean flag = false;
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement(
                    "select * from selfExamTransaction where selfExamId=? and userId=?");
            preparedStatement.setInt(1, selfExamId);
            preparedStatement.setInt(2, userId);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                flag = true;
            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println("第一次登陆；");
        }
        return flag;
    }

    @Override
    public Boolean checkCommit(Integer selfExamId, Integer userId) {
        Boolean flag = false;
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement(
                    "select * from selfExamTransaction where selfExamId=? and userId=? and spendTime is not null");
            preparedStatement.setInt(1, selfExamId);
            preparedStatement.setInt(2, userId);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                flag = true;
            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println("作业已提交；");
        }
        return flag;
    }


    public Boolean commit(Integer userId, String answerUrl) {
        Boolean flag = false;
        try {
            Date nowDate = new Date();
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
//            String format = df.format(d2);
//            Date nowDate = df.parse(format);
            String date = df2.format(nowDate);
            System.out.println("nowDate is :" + nowDate);
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement(
                    "select startTime from selfExamTransaction where userId=? and date_format(startTime,'%Y-%m-%d')=?;");
            preparedStatement.setInt(1, userId);
            preparedStatement.setDate(2, java.sql.Date.valueOf(date));
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                Date d1 = resultSet.getTimestamp("startTime");
                Date startTime = df.parse(d1.toString());
                System.out.println("startTime is :" + startTime);
//                long minutes=(date2.getTime()-date1.getTime())/(1000*60);
                long spendTime = (nowDate.getTime() - startTime.getTime()) / (1000 * 60);
                System.out.println("spendTime is :" + spendTime);
                PreparedStatement pst = cn.prepareStatement(
                        "update selfExamTransaction set answerUrl=?,spendTime=? where userId=? and answerUrl is null;");
                pst.setString(1, answerUrl);
                pst.setString(2, spendTime + "minutes");
                pst.setInt(3, userId);
                pst.executeUpdate();
                flag = true;

            }

        DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    public List searchMyQuestion() {
        List<Question> questions = null;
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement pst = cn.prepareStatement("select * from question");
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                if (questions == null) {
                    questions = new ArrayList<>();
                }
                Question question = new Question();
                question.setId(rs.getInt("id"));
                question.setContent(rs.getString("content"));
                questions.add(question);
            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return questions == null ? null : questions;
    }

    @Override
    public void searchMyAnswer() {

    }

    @Override
    public void studentsWork() {

    }

    public List getSelfExamToTable() {
        List<SelfExam> selfExams = null;
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement pst = cn.prepareStatement("select * from selfExam");
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                if (selfExams == null) {
                    selfExams = new ArrayList<SelfExam>();
                }
                SelfExam selfExam = new SelfExam();
                selfExam.setId(rs.getInt("id"));
                selfExam.setClassId(rs.getInt("classId"));
                selfExam.setDate(rs.getDate("date"));
                selfExam.setQuestionId(rs.getString("questionId"));

                selfExams.add(selfExam);
            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return selfExams == null ? null : selfExams;
    }


    public List searchSelfQuestion() {
        List<SelfQuestion> selfQuestions = null;
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement("select * from selfExam");
            ResultSet resultSet = preparedStatement.executeQuery();
            List<SelfExam> selfExams = null;
            while (resultSet.next()) {
                if (selfExams == null) {
                    selfExams = new ArrayList<>();
                }
                SelfExam selfExam = new SelfExam();
                selfExam.setQuestionId(resultSet.getString("questionId"));
                selfExam.setDate(resultSet.getDate("date"));
                selfExams.add(selfExam);
            }

            for (int i = 0; i < selfExams.size(); i++) {
                String questionIds = selfExams.get(i).getQuestionId();
                Date date = selfExams.get(i).getDate();

                Split split = new Split();
                List<Integer> questionIdList = null;
                String content = "";
                questionIdList = split.getSplit(questionIds);
                System.out.println("questionIdList :" + questionIdList.toString());
                for (int j = 0; j < questionIdList.size(); j++) {
                    SelfExamDao selfExamDao = new SelfExamDaoImpl();
                    Question question = new Question();
                    question.setContent(j+1 + ":    " + selfExamDao.getQuestionById(questionIdList.get(j)) + "\n");
                    content += question.getContent();
                }
                System.out.println("content is : " + content);
                if (selfQuestions == null) {
                    selfQuestions = new ArrayList<>();
                }
                SelfQuestion selfQuestion = new SelfQuestion();
                selfQuestion.setQuestion(content);
                selfQuestion.setDate(date);
                selfQuestions.add(selfQuestion);
            }
        DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return selfQuestions;
    }


    public String searchAnswerUrlById(int id) {
        SelfExamTransaction selfExamTransaction = new SelfExamTransaction();
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement pst = cn.prepareStatement(
                    "select answerUrl from selfExamTransaction where id=?");
            pst.setInt(1, id);
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                selfExamTransaction.setAnswerUrl(rs.getString("answerUrl"));
            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return selfExamTransaction.getAnswerUrl();
    }

    @Override
    public List getContentByDate(String date) {
        List<SelfStudentHomework> studentHomeworkLIst = new ArrayList<>();
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement(
                    "select * from selfExamTransaction where date_format(startTime,'%Y-%m-%d')=?;");
            preparedStatement.setDate(1, java.sql.Date.valueOf(date));
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                SelfStudentHomework selfStudentHomework = new SelfStudentHomework();
                Integer transactionId = resultSet.getInt("id");
                Integer userId = resultSet.getInt("userId");
                Integer score = resultSet.getInt("score");
                String answerUrl = resultSet.getString("answerUrl");
                String spendTime = resultSet.getString("spendTime");
                String userName = getUserNameById(userId);
                selfStudentHomework.setTransactionId(transactionId);
                selfStudentHomework.setName(userName);
                selfStudentHomework.setScore(score);
                selfStudentHomework.setAnswerUrl(answerUrl);
                selfStudentHomework.setSpendTime(spendTime);
                studentHomeworkLIst.add(selfStudentHomework);

            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return studentHomeworkLIst;
    }


    @Override
    public String getQuestionById(Integer id) {
        Question question = new Question();
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement(
                    "select content from question where id=?");
            preparedStatement.setInt(1, id);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                question.setContent(resultSet.getString("content"));
            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return question.getContent();
    }

    public String getUserNameById(Integer userId) {
        String userName = "";
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement("select name from user where id=?");
            preparedStatement.setInt(1, userId);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                userName = resultSet.getString("name");
            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userName;
    }

    @Override
    public String getQuestionByDate(String date) {
        String questionIds = null;
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement(                    "select questionId from selfExam where date=?");
            preparedStatement.setString(1, date);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                questionIds = resultSet.getString("questionId");
            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return questionIds;
    }

    @Override
    public Integer getUserIdFromTransaction(Integer transactionId) {
        Integer userId = null;
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement(                    "select userId from selfExamTransaction where id=? ;");
            preparedStatement.setInt(1, transactionId);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                userId = resultSet.getInt("userId");
            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("winner Id is :" + userId);
        return userId;
    }

    @Override
    public Boolean setWinner(String date, Integer winnerId) {
        Boolean flag = false;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            String date2=sdf.format(date);
            System.out.println("date :" + date);
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement(                    "update selfExam set winnerId =?  where date=? ;");
            preparedStatement.setInt(1, winnerId);
            preparedStatement.setString(2, date);
            preparedStatement.executeUpdate();
            flag = true;
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            System.out.println("上传失败！");
        }
        return flag;
    }

    @Override
    public Integer getSelfExamIdDate(String date,Integer clazzId) {
        Integer selfExamId = null;
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement(                    "select id from selfExam where date=? and classId=?");
            preparedStatement.setString(1, date);
            preparedStatement.setInt(2, clazzId);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                selfExamId = resultSet.getInt("id");
            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return selfExamId;
    }

    @Override
    public String getUrlById(Integer id) {
        String answerUrl = "";
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement(                    "select answerUrl from selfExamTransaction where id=?");
            preparedStatement.setInt(1, id);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                answerUrl += resultSet.getString("answerUrl");
            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return answerUrl;
    }

    @Override
    public void setGrade(Integer transactionId, Integer score) {
        try {
            Connection cn=DBUtilPool.getConnection();
            PreparedStatement preparedStatement = cn.prepareStatement(                    "update selfExamTransaction set score=? where id=?");
            preparedStatement.setInt(1, score);
            preparedStatement.setInt(2, transactionId);
            preparedStatement.executeUpdate();
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

